package wicket.example.components.table.test.navigator;

import java.util.List;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.ChoiceRenderer;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.markup.html.navigation.paging.IPageable;
import org.apache.wicket.markup.html.navigation.paging.PagingNavigator;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;

public abstract class TableNavigator extends PagingNavigator
{

   private static final long   serialVersionUID        = 1L;

   private final IModel<String> totalItemsModel;
   private final List<DropDownEntry> dropDownEntries;
   private DropDownEntry selectedEntry;
   
   public TableNavigator(final String id, IPageable pageable, final IModel<String> totalItemsModel, final List<DropDownEntry> dropDownEntries, DropDownEntry selectedEntry)
   {
      super(id, pageable);
      this.setOutputMarkupId(true);
      this.totalItemsModel = totalItemsModel;
      this.dropDownEntries = dropDownEntries;
      this.selectedEntry = selectedEntry;
   }

   @Override
   protected void onInitialize()
   {
      super.onInitialize();
      add(new Label("entriesCount", totalItemsModel));

      IChoiceRenderer<DropDownEntry> renderer = new ChoiceRenderer<DropDownEntry>()
      {

         private static final long serialVersionUID = 1L;

         @Override
         public Object getDisplayValue(DropDownEntry object)
         {
            return String.format("%s %s", object.getEntriesPerPageNumber(), object.getEntriesPerPageTextValue());
         }
      };

      DropDownChoice<DropDownEntry> entriesCountPerPageDropDown = new DropDownChoice<DropDownEntry>("entriesCountPerPageDropDown",
            new PropertyModel<DropDownEntry>(this, "selectedEntry"), dropDownEntries, renderer);
      entriesCountPerPageDropDown.add(new AjaxFormComponentUpdatingBehavior("onchange")
      {

         private static final long serialVersionUID = 1L;

         @Override
         protected void onUpdate(AjaxRequestTarget target)
         {
            target.add(TableNavigator.this);
            TableNavigator.this.onDropDownValueChanged(target, selectedEntry);
         }

      });
      entriesCountPerPageDropDown.setNullValid(false);
      add(entriesCountPerPageDropDown);
   }

   public abstract void onDropDownValueChanged(AjaxRequestTarget target, DropDownEntry entry);

}
